package com.app.newiptv.presenter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.app.newiptv.R;
import com.app.newiptv.base.MyApplication;
import com.app.newiptv.bean.KeyBoard;
import com.app.newiptv.bean.SearchBean;
import com.app.newiptv.callback.RequestCallback;
import com.app.newiptv.service.AHservice;
import com.app.newiptv.utils.APPLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Shinelon on 2017/9/15.
 */

public class SearchPresenter implements RequestCallback<SearchBean>, Handler.Callback {
    private boolean isDisplayed;
    private Callback callback;
    public List<SearchBean> listContent;
    private int[] keyboardList;
    private Activity mActivity;
    private View mainView;
    private RelativeLayout mActivity_search;
    private RelativeLayout keyView;
    private View keyboardview;
    private RelativeLayout keybgView;
    private boolean isKey = false;
    private TextView top_key_btn;
    private TextView centre_key_btn;
    private TextView right_key_btn;
    private TextView left_key_btn;
    private TextView bottom_key_btn;
    private View focusView;
    private List<KeyBoard> keyBoards;
    private ISetViewHolder mViewHolder;
    private Handler handler;
    private int mPosition;


    public SearchPresenter(Activity mActivity) {
        this.mActivity = mActivity;
        handler = new Handler(this);
        initKeyBoard();
    }

    public void setView(View mainView, RelativeLayout mActivity_search) {
        this.mainView = mainView;
        this.mActivity_search = mActivity_search;
    }

    @Override
    public void onLoadComplete(String contentID, int pageNumber, int count, List<SearchBean> contents) {
        if (callback == null || !isDisplayed) {
            APPLog.printInfo("onLoadComplete:callback :");
            return;
        }
        listContent = contents;
        callback.onMovieCompleted(SearchPresenter.this, count);
    }

    @Override
    public void onLoading(String contentID) {

    }

    @Override
    public void onFailed(String code, String msg) {
        if ("9999".equals(code)) {
            //没有搜到结果
            callback.onMovieCompleted(SearchPresenter.this, 0);
        }
    }

    public Bundle getParams(int position) {
        Bundle bundle = new Bundle();
        SearchBean searchBean = listContent.get(position);
        Log.d("tag", "---------" + searchBean.toString());
        bundle.putInt("id", searchBean.getId());
        return bundle;
    }

    public boolean getVodType(int position) {
        SearchBean searchBean = listContent.get(position);
        if (searchBean.getTotal_episode() == 1) {
            return true;
        }
        return false;
    }

    public boolean getTelType(int position) {
        SearchBean searchBean = listContent.get(position);
        if (searchBean.getTotal_episode() > 1) {
            return true;
        }
        return false;
    }

    public void setDisplayed(boolean displayed) {
        isDisplayed = displayed;
    }

    //加载数据
    public void loadItem(String url, Callback callback) {
        this.callback = callback;
        AHservice service = new AHservice();
        service.searchCallback(url, this);
    }

    public void loadKeyboard(Callback callback) {
        keyboardList = new int[]{R.mipmap.key1, R.mipmap.key2, R.mipmap.key3, R.mipmap.key4, R.mipmap.key5, R.mipmap.key6, R.mipmap.key7, R.mipmap.key8, R.mipmap.key9, R.mipmap.key_clear, R.mipmap.key0, R.mipmap.key_delete,};
        callback.onKeyboardCompleted(this, keyboardList.length);
    }

    public void searchPosition(int position) {

    }

    public void keyboardPosition(final int position, View view) {
        this.mPosition = position;
        callback.onSearchCompleted(this);
        int[] xy = new int[2];
        view.getLocationInWindow(xy);
        focusView = view;
        Toast.makeText(mActivity, "--------x-------" + xy[0] + "-----y----" + xy[1], Toast.LENGTH_SHORT).show();
        int w = view.getWidth() / 3 / 2;
        int h = view.getHeight() / 3 / 2;
        Log.d("tag", "---------w-------" + w);
        Log.d("tag", "---------h-------" + h);
        w = xy[0] - w;
        h = xy[1] - h;
//        keyView = new RelativeLayout(mContext);
        keyboardview = LayoutInflater.from(mActivity).inflate(R.layout.keyboardview, null);
        keybgView = (RelativeLayout) keyboardview.findViewById(R.id.key_bg_view);
        top_key_btn = (TextView) keyboardview.findViewById(R.id.top_key_btn);
        centre_key_btn = (TextView) keyboardview.findViewById(R.id.centre_key_btn);
        right_key_btn = (TextView) keyboardview.findViewById(R.id.right_key_btn);
        left_key_btn = (TextView) keyboardview.findViewById(R.id.left_key_btn);
        bottom_key_btn = (TextView) keyboardview.findViewById(R.id.bottom_key_btn);

        top_key_btn.setTypeface(MyApplication.face);
        centre_key_btn.setTypeface(MyApplication.face);
        right_key_btn.setTypeface(MyApplication.face);
        left_key_btn.setTypeface(MyApplication.face);
        bottom_key_btn.setTypeface(MyApplication.face);

        if (keyBoards != null && position < keyBoards.size()) {
            left_key_btn.setText(keyBoards.get(position).getLeftNumber());
            top_key_btn.setText(keyBoards.get(position).getTopNumber());
            right_key_btn.setText(keyBoards.get(position).getRigthNumber());
            centre_key_btn.setText(keyBoards.get(position).getCenterNumber());
            bottom_key_btn.setText(keyBoards.get(position).getBottomNumber());
        }
        switch (position) {
            case 0:
                mViewHolder.setSearchEdt("1", position);
                break;
            case 9:
                mViewHolder.setSearchEdt("", position);
                break;
            case 10:
                mViewHolder.setSearchEdt("0", position);
                break;
            case 11:
                mViewHolder.setSearchEdt("", position);
                break;
        }

        centre_key_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = centre_key_btn.getText().toString().trim();
                keybgView.setBackgroundResource(R.mipmap.qishi);
                centre_key_btn.requestFocus();
                mViewHolder.setSearchEdt(text, position);
            }
        });

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(180, 180);
        params.setMargins(w, h, 0, 0);
        keyboardview.setLayoutParams(params);
        if (position > 0 && position < 9) {
            isKey = true;
            mActivity_search.addView(keyboardview);
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("tag", "-------keyCode--------" + keyCode + "------isKey------" + isKey);
        int keyDown = event.getAction();
        if (isKey) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && keyDown == KeyEvent.ACTION_DOWN) {
                keybgView.setBackgroundResource(R.mipmap.left);
                left_key_btn.requestFocus();

                String text = left_key_btn.getText().toString().trim();
                mViewHolder.setSearchEdt(text, mPosition);
                handler.sendEmptyMessageDelayed(0, 200);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && keyDown == KeyEvent.ACTION_DOWN) {
                keybgView.setBackgroundResource(R.mipmap.right);
                right_key_btn.requestFocus();

                String text = right_key_btn.getText().toString().trim();
                mViewHolder.setSearchEdt(text, mPosition);
                handler.sendEmptyMessageDelayed(0, 200);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP && keyDown == KeyEvent.ACTION_DOWN) {
                keybgView.setBackgroundResource(R.mipmap.top);
                top_key_btn.requestFocus();

                String text = top_key_btn.getText().toString().trim();
                mViewHolder.setSearchEdt(text, mPosition);
                handler.sendEmptyMessageDelayed(0, 200);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && keyDown == KeyEvent.ACTION_DOWN) {
                if (mPosition == 6 || mPosition == 8) {
                    keybgView.setBackgroundResource(R.mipmap.down);
                    bottom_key_btn.requestFocus();

                    String text = bottom_key_btn.getText().toString().trim();
                    mViewHolder.setSearchEdt(text, mPosition);
                    handler.sendEmptyMessageDelayed(0, 200);
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_BACK && keyDown == KeyEvent.ACTION_DOWN) {
                mActivity_search.removeView(keyboardview);
                isKey = false;
                focusView.requestFocus();
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && keyDown == KeyEvent.ACTION_DOWN) {
                Toast.makeText(mActivity, "确定", Toast.LENGTH_SHORT).show();
                return true;
            }
        } else {
            if (keyCode == KeyEvent.KEYCODE_BACK && keyDown == KeyEvent.ACTION_DOWN) {
                if (mActivity != null) {
                    mActivity.finish();
                }
                return true;
            }
        }
        return false;
    }

    public void onBindMainChanelView(SearchViewHolder holder, int position) {
        if (!isDisplayed) {
            return;
        }
        holder.setprogramName(listContent.get(position).getName());
    }

    public void onBindKeyBoardChanelView(MainViewHolder holder, int position) {
        if (!isDisplayed) {
            return;
        }
        holder.setkeyboardImg(keyboardList[position]);
    }


    private void initKeyBoard() {
        keyBoards = new ArrayList<>();
        keyBoards.add(new KeyBoard("1", "", "", "", ""));
        keyBoards.add(new KeyBoard("2", "A", "B", "C", ""));
        keyBoards.add(new KeyBoard("3", "D", "E", "F", ""));
        keyBoards.add(new KeyBoard("4", "G", "H", "I", ""));
        keyBoards.add(new KeyBoard("5", "J", "K", "L", ""));
        keyBoards.add(new KeyBoard("6", "M", "N", "O", ""));
        keyBoards.add(new KeyBoard("7", "P", "Q", "R", "S"));
        keyBoards.add(new KeyBoard("8", "T", "U", "V", ""));
        keyBoards.add(new KeyBoard("9", "W", "X", "Y", "Z"));
    }

    public void setSearchData(ISetViewHolder viewHolder) {
        this.mViewHolder = viewHolder;
    }

    @Override
    public boolean handleMessage(Message message) {
        keybgView.setBackgroundResource(R.mipmap.qishi);
        centre_key_btn.requestFocus();
        return false;
    }


    public interface Callback {
        void onError(int code, String msg);

        void onMovieCompleted(SearchPresenter presenter, int count);

        void onKeyboardCompleted(SearchPresenter presenter, int count);

        void onSearchCompleted(SearchPresenter presenter);
    }

    public interface MainViewHolder {
        void setkeyboardImg(int image);
    }

    public interface SearchViewHolder {
        void setprogramName(String programName);
    }

    public interface ISetViewHolder {
        void setSearchEdt(String text, int type);
    }


}
